/**
 *    文件上传组件
 *    uploadSuccess : 上传成功调用，给父组件设置值（父组件直接form获取，可做必填项校验）
 *    fileUrl :  父组件把自身的值传递回来，用来回显数据
 *
 *    fileMaxSize： 默认10M  文件大小限制
 *    suffix  默认为空，表示支持全类型   =》  "mp3,mp4,jpg,png"
 *    uploadUrl:    默认/common/upload/all文件上传路径
 *    tag : 默认为button   上传文件的显示  按钮button或者a标签     button/a
 *    text: 默认为上传    按钮或者a标签显示的内容
 *
 */
import React from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Upload, Button } from 'antd';
import { windowUrl } from "../../../../public/global";
import { getToken } from "@/utils/utils";
import { getOptAuthHeaders } from '@/utils/common';

@Form.create()
export default class PateoFileUpload extends React.Component<any,any> {
  state = {
    fileList: [], // 文件列表,只用在upload
  };
  //  文件上传
  handleFileChange = (info) => {
    const { uploadSuccess } = this.props;
    let { fileList, file } = info;
    fileList = fileList.slice(-1);
    if (file.status === 'done' && file.response && file.response.statusCode === "0" && file.response.data) {
      message.success(`${file.name} 上传成功`);
      uploadSuccess(file.response.data.fileUrl);
    } else if(file.status === 'done' && file.response && file.response.statusCode !== "0"){
      message.error(file.response.statusMessage);
      this.setState({ fileList: [] });
      return;
    } else if (file.status === 'removed') {
      message.success("删除成功");
      return;
    } else if (file.status === 'error') {
      message.error(`${file.name} 上传失败`);
      this.setState({ fileList: [] });
      return;
    } else if (!file.status) {
      this.setState({ fileList: [] });
      return;
    }
    this.setState({ fileList });
  };
  // 文件删除
  handleRemove = () =>{
    const { uploadSuccess } = this.props;
    this.setState({ fileList: [] });
    uploadSuccess(undefined);
  };
  // 文件上传前校验
  beforeFileUpload = (file) => {
    const { fileMaxSize = 10, suffix = "" } = this.props;
    // 文件后缀校验
    if(suffix){
      let flag = false;
      const suffixItem = suffix.split(",");
      suffixItem.forEach(item => {
       if(file.name.endsWith(`.${item}`)) flag = true;
      });
      if(!flag){
        message.error(`上传文件格式有误，仅支持${suffix}文件！`);
        return false;
      }
    }
    if (file.size / 1024 / 1024 > fileMaxSize) {
      message.error(`文件大小不能大于${fileMaxSize}MB！`);
      return false;
    }
    return true;
  };
  //  文件回显
  convertValueToFileList = (fileUrl) => {
    const files = [];
    if (fileUrl) {
      files.push({
        uid: "-1",
        name: fileUrl,
        status: 'done',
        url: fileUrl,
        response:{ data: { fileUrl }},
      });
    }
    return files;
  };

  static getDerivedStateFromProps(nextProps:any, prevState: any) {
     // 不存在fileUrl时清空fileList
    if(!nextProps.fileUrl && prevState.fileList[0] && prevState.fileList[0].response && prevState.fileList[0].response.data && prevState.fileList[0].response.data.fileUrl){
       return {
         fileList:[]
       }
    }
    return null;
  }
  render() {
    const { fileList } = this.state;
    // 公共的文件上传后台默认最大大小为100M，类型为除图片格式外全类型
    const { fileUrl, uploadUrl = "/common/upload/all", fileMaxSize = 10, suffix = "",tag = "button", text = "上传", listType="text" } = this.props;
    // 此处可用于拼接url实现后端同时校验文件大小以及类型
    const str = `${windowUrl}${uploadUrl}`;
    return (
      <Upload
        listType={listType}
        headers={{
          OptAuthorization: `${getToken()}`,
          ...getOptAuthHeaders()
        }}
        action={str}
        multiple={false}
        showUploadList={{ showPreviewIcon: false }}
        fileList={fileUrl ? this.convertValueToFileList(fileUrl) : fileList}
        onChange={this.handleFileChange}
        beforeUpload={this.beforeFileUpload}
        onRemove={()=> this.handleRemove()}
      >
        {
          !fileUrl ? (
              tag === "button" ? (
                  <Button style={{ marginTop: 6 }} size="small">
                    <PlusOutlined />{text}
                  </Button>
              ) : (
                  <a style={{ marginTop: 6 }}>{text}</a>
              )
          ): null
        }
  </Upload>
    );
  }
}
